import React, { Component } from 'react';
import { View, Image, StyleSheet, ActivityIndicator } from 'react-native';
import FastImage from 'react-native-fast-image';

class AsyncImage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loaded: false,
        };
    }

    componentDidMount() {

    }

    render() {
        const {
            source,
            defaultSource,
            style,
            loadingIndicator = true,
            loadingColor = '#999',
            ...rest
        } = this.props;

        // 如果没有网络图片或加载出错，使用默认图片
        const displaySource = (!source || !source.uri)
            ? defaultSource
            : source;

        return (
            <View style={[styles.container, style]}>

                {!this.state.loaded && (
                    <Image
                        source={defaultSource}
                        style={[style, styles.image, { position: 'absolute', zIndex: 1000 }]}
                    />
                )}

                {
                    displaySource && displaySource.uri && displaySource.uri.length > 0 ?
                        <FastImage
                            style={[style, styles.image]}
                            source={{
                                uri: displaySource.uri,
                                priority: FastImage.priority.normal,
                            }}
                            onLoad={() => {
                                this.setState({ loaded: true });
                            }}
                            resizeMode={FastImage.resizeMode.cover}
                            {...rest}
                        />
                        :
                        null
                }

            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        position: 'relative',
        justifyContent: 'center',
        alignItems: 'center',
    },
    image: {
        width: '100%',
        height: '100%',
    },
    loadingContainer: {
        position: 'absolute',
        justifyContent: 'center',
        alignItems: 'center',
    },
});

export default AsyncImage;